package com.wl.network.demo06;

import java.net.DatagramPacket;
import java.net.DatagramSocket;

public class TalkReceive implements Runnable{
    DatagramSocket socket = null;

    private String msgSay;
    private int port;


    public TalkReceive(int port,String msgSay) {
        this.port = port;
        this.msgSay = msgSay;
        try {
            socket = new DatagramSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            try {
                byte[] container = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(container,0,container.length);
                socket.receive(datagramPacket);
                //断开连接
                byte[] data = datagramPacket.getData();
                String datas = new String(data, 0, datagramPacket.getLength());
                System.out.println(msgSay+datas);
                if (datas.equals("0")){
                    break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
